import * as echarts from '../../ec-canvas/echarts.js';

const app = getApp()
const db = wx.cloud.database({
  env: 'cloud1-2g6vpgs796710242'
})
const _ = db.command
var sdict = []
var ssum = []
var nsum = []

function setOption(chart,rdata,ldata) {
  var option = {
    //图例
    legend: {
      data: ldata
    },
    singleAxis: {
      top: 18,
      bottom: 18,
      axisTick: {},
      axisLabel: {
        interval:3
      },
      type: 'time',
      axisPointer: {
        animation: true,
        label: {
          show: true
        }
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          opacity: 0.2
        }
      }
    },
    series: [{
        type: 'themeRiver',
        itemStyle: {
          emphasis: {
            shadowBlur: 20,
            shadowColor: 'rgba(0, 0, 0, 0.8)'
          }
        },
        data:rdata
      }]
  };
  chart.setOption(option);
  return chart;
}

function sortByInt (array, key) {
  return array.sort(function (b, a) {
    var x = a[key]
    var y = b[key]
    return y - x
  })
}

Page({
  data: {
    profileP:"",
    planet_info:[],
    key:"",
    cava:app.globalData.ava,
    ec: {
      // onInit: initChart
      lazyLoad: true
    },
    storage:[]
  },

  initpie:function(rdata,ldata){
    let ecComponent = this.selectComponent('#mychart-dom-pie');
    ecComponent.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      canvas.setChart(chart);
      //调用设定EChart报表状态的函数，并且把从后端拿到的数据传过去
      setOption(chart,rdata,ldata);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return chart;
    });
  },

  onLoad: function (options) {
    var user = wx.getStorage({
      key:'user',
      success: (res)=> {
        console.log("查询用户信息缓存",res.data)
        this.setData({
          storage:res.data,
          cava:res.data.ava
        })
      }
    })
    console.log("planet传值", options)
    var id = options.id
    db.collection('cp_list')
    .doc(id)
    .get()
    .then(res=>{
      console.log(res)
      this.setData({
        planet_info:res.data
      })
      //CTR自增
      db.collection("cp_list")
      .doc(id)
      .update({
        data:{
          CTR:_.inc(1)
        }
      })
      .then(res=>{
        console.log("CTR自增成功",res)
      })
      if (!this.data.storage.name=="") {
        console.log('用户信息已授权',user)
        this.setData({
          hasUserInfo: true,
          userInfo: user,
        })
        console.log("用户信息", this.data.userInfo)
        console.log("全局openid",app.globalData.openid)
        
        db.collection("User")
        .where({
          _openid:app.globalData.openid
        })
        .get()
        .then(res=>{
          console.log("用户信息",res)
          var aimcp = this.data.planet_info.title
          for (var i = 0; i < res.data[0].common.length; i++) {
            if (res.data[0].common[i].name==aimcp) {
              db.collection("User")
              .where({
                _openid:app.globalData.openid,
                'common.name':aimcp
              })
              .update({
                data:{
                  "common.$.count":res.data[0].common[i].count+1
                }
              })
              .then(res=>{
                console.log("使用频次更新成功",res)
              })
              .catch(err=>{
                console.log(err)
              })
            }
          }
        })
      } else {
        console.log("无缓存用户信息")
      }
      //图表数据初始化
      var rdata = [
      ['2015/11/08', 10, 'DQ'], ['2015/11/09', 15, 'DQ'], ['2015/11/10', 35, 'DQ'],
      ['2015/11/14', 7, 'DQ'], ['2015/11/15', 2, 'DQ'], ['2015/11/16', 17, 'DQ'],
      ['2015/11/17', 33, 'DQ'], ['2015/11/18', 40, 'DQ'], ['2015/11/19', 32, 'DQ'],
      ['2015/11/20', 26, 'DQ'], ['2015/11/21', 35, 'DQ'], ['2015/11/22', 40, 'DQ'],
      ['2015/11/23', 32, 'DQ'], ['2015/11/24', 26, 'DQ'], ['2015/11/25', 22, 'DQ'],
      ['2015/11/08', 35, 'TY'], ['2015/11/09', 36, 'TY'], ['2015/11/10', 37, 'TY'],
      ['2015/11/11', 22, 'TY'], ['2015/11/12', 24, 'TY'], ['2015/11/13', 26, 'TY'],
      ['2015/11/14', 34, 'TY'], ['2015/11/15', 21, 'TY'], ['2015/11/16', 18, 'TY'],
      ['2015/11/17', 45, 'TY'], ['2015/11/18', 32, 'TY'], ['2015/11/19', 35, 'TY'],
      ['2015/11/20', 30, 'TY'], ['2015/11/21', 28, 'TY'], ['2015/11/22', 27, 'TY'],
      ['2015/11/23', 26, 'TY'], ['2015/11/24', 15, 'TY'], ['2015/11/25', 30, 'TY'],
      ['2015/11/26', 35, 'TY'], ['2015/11/27', 42, 'TY'], ['2015/11/28', 42, 'TY'],
      ['2015/11/08', 21, 'SS'], ['2015/11/09', 25, 'SS'], ['2015/11/10', 27, 'SS'],
      ['2015/11/11', 23, 'SS'], ['2015/11/12', 24, 'SS'], ['2015/11/13', 21, 'SS'],
      ['2015/11/14', 35, 'SS'], ['2015/11/15', 39, 'SS'], ['2015/11/16', 40, 'SS'],
      ['2015/11/17', 36, 'SS'], ['2015/11/18', 33, 'SS'], ['2015/11/19', 43, 'SS'],
      ['2015/11/20', 40, 'SS'], ['2015/11/21', 34, 'SS'], ['2015/11/22', 28, 'SS'],
      ['2015/11/14', 7, 'QG'], ['2015/11/15', 2, 'QG'], ['2015/11/16', 17, 'QG'],
      ['2015/11/17', 33, 'QG'], ['2015/11/18', 40, 'QG'], ['2015/11/19', 32, 'QG'],
      ['2015/11/20', 26, 'QG'], ['2015/11/21', 35, 'QG'], ['2015/11/22', 40, 'QG'],
      ['2015/11/23', 32, 'QG'], ['2015/11/24', 26, 'QG'], ['2015/11/25', 22, 'QG'],
      ['2015/11/26', 16, 'QG'], ['2015/11/27', 22, 'QG'], ['2015/11/28', 10, 'QG'],
      ['2015/11/08', 10, 'SY'], ['2015/11/09', 15, 'SY'], ['2015/11/10', 35, 'SY'],
      ['2015/11/11', 38, 'SY'], ['2015/11/12', 22, 'SY'], ['2015/11/13', 16, 'SY'],
      ['2015/11/14', 7, 'SY'], ['2015/11/15', 2, 'SY'], ['2015/11/16', 17, 'SY'],
      ['2015/11/17', 33, 'SY'], ['2015/11/18', 40, 'SY'], ['2015/11/19', 32, 'SY'],
      ['2015/11/20', 26, 'SY'], ['2015/11/21', 35, 'SY'], ['2015/11/22', 4, 'SY'],
      ['2015/11/23', 32, 'SY'], ['2015/11/24', 26, 'SY'], ['2015/11/25', 22, 'SY'],
      ['2015/11/26', 16, 'SY'], ['2015/11/27', 22, 'SY'], ['2015/11/28', 10, 'SY'],
      ['2015/11/08', 10, 'DD'], ['2015/11/09', 15, 'DD'], ['2015/11/10', 35, 'DD'],
      ['2015/11/11', 38, 'DD'], ['2015/11/12', 22, 'DD'], ['2015/11/13', 16, 'DD'],
      ['2015/11/14', 7, 'DD'], ['2015/11/15', 2, 'DD'], ['2015/11/16', 17, 'DD'],
      ['2015/11/17', 33, 'DD'], ['2015/11/18', 4, 'DD'], ['2015/11/19', 32, 'DD'],
      ['2015/11/20', 26, 'DD'], ['2015/11/21', 35, 'DD'], ['2015/11/22', 40, 'DD'],
      ['2015/11/23', 32, 'DD'], ['2015/11/24', 26, 'DD'], ['2015/11/25', 22, 'DD'],
      ['2015/11/26', 16, 'DD'], ['2015/11/27', 22, 'DD'], ['2015/11/28', 10, 'DD']
      ]
      var ldata = ['DQ', 'TY', 'SS', 'QG', 'SY', 'DD']
      this.initpie(rdata,ldata)
    })
    .catch(err=>{
      console.log("行星库数据获取失败",err)
    })
  },

  // onReady: function () {
  //   this.ecComponent = this.selectComponent('mychart-dom-pie');
  // },

  display(event) {
    var key = event.detail.value
    this.setData({
      key: key
    })
    console.log(this.data.key)
  },

  search() {
    sdict.splice(0, sdict.length)
    ssum.splice(0, ssum.length)
    nsum.splice(0, nsum.length)
    console.log("触发search")
    if (this.data.key !== '') {
      console.log(this.data.key)
      wx.request({
        header: {
          "content-type": "application/json",
        },
        method: "GET",
        url: "https://xueshu.baidu.com/usercenter/data/paperreco?cmd=batch_get_kw_chart&kw_list="+this.data.key+"&_token=fc55526ac7bb6e3ab419fe69e594a13130b3c2679074fc620eeb6745dc6aa422&_ts=1641370793&_sign=718e5448c7838507e1615c1dd7d60081",
        success: res => {
          var datalength = res.data.data.current_kw_data.trend.totalArticle
          if (datalength==0) {
            wx.showToast({ title: '未检索到相关领域数据', icon: 'none' });
          } else {
            console.log("成功", res.data);
            var bat = JSON.stringify(res.data)
            var bd_output = JSON.parse(bat)
            var association_array = bd_output.data.current_kw_data.association.chartData
            var newArrByInt_tops = sortByInt(association_array,"paperNum")
            var newArrByInt_subset = sortByInt(newArrByInt_tops.slice(-1)[0]["data"],"value")
            console.log("按paper ( 数字 )排序：",newArrByInt_tops.slice(-1))
            console.log("成功", bd_output);
            this.setData({
              tops:newArrByInt_tops.slice(-1)[0]["name"],
              tops_num:newArrByInt_tops.slice(-1)[0]["paperNum"],
              tops_year_maxp:newArrByInt_subset.slice(-1)[0]["time"],
              tops_value_maxp:newArrByInt_subset.slice(-1)[0]["value"],
              bottoms:newArrByInt_tops[0]["name"],
              bottoms_num:newArrByInt_tops[0]["paperNum"]
            })
            bd_output.data.current_kw_data.association.chartData.forEach(element => {
              nsum = nsum.concat(element.name)
              element.data.slice(-15).forEach(simple =>{
                var slist = [simple.time,simple.value,element.name]
                sdict.push(slist)
              })
            })
            ssum = ssum.concat(sdict)
            var rdata = ssum
            var ldata = nsum
            this.initpie(rdata,ldata)
            // new Promise(function (resolve) {
            //   resolve();
            // }).then(()=> {
            // }).then(()=>{
            // })
          }
        },
        fail: err => {
          console.log("错误", err);
        }
      })
    } else {
      wx.showToast({ title: '请输入关键词', icon: 'none' });
    }
  },

})